<template>
    <Popup ref="popupRef" :form-data="formData" :rules="rules" :title="modeTitle" @submit="handleSubmit"
        @cancel="handleCancel">
        <a-form-item label="名称" field="name">
            <a-input v-model="formData.name" placeholder="请输入部门名称" />
        </a-form-item>
        <a-form-item label="所属组织" field="organization_id">
            <a-select v-model="formData.organization_id" :options="options" placeholder="请选择所属组织" />
        </a-form-item>
        
    </Popup>
</template>

<script setup lang="ts">
import Popup from '@/components/Popup/index.vue'
import { addDepartment, editDepartment } from '@/api/system/organize/department'
import { getOrganizationList } from '@/api/system/organize/company'
const popupRef = ref<InstanceType<typeof Popup>>()
const emits = defineEmits(['success'])
interface FormData {
    id?: number | null
    name: string
    organization_id: number | null
    description: string
}

const formData = reactive<FormData>({
    id: null,
    name: '',
    organization_id:null,
    description: ''
})

const rules = {
    name: [
        { required: true, message: '请输入部门名称' }
    ],
    
}

const mode = ref<string | 'add' | 'edit'>('add')
const modeTitle = computed(() => {
    return mode.value === 'add' ? '新增' : '编辑'
})


const open = (type: string | 'add' | 'edit') => {
    mode.value = type
    popupRef.value?.open()
    nextTick(() => {
        getOrgList()
    })
}

const options = ref<any[]>([])
const getOrgList = async () => {
    const res = await getOrganizationList()
    options.value = res.map((item: any) => ({
        label: item.name,
        value: item.id
    }))
}


const setFormData = async (record: Record<any, any>) => {
    if (record) {
        // 使用解构赋值来合并数据

        for (const key in formData) {
            if (record[key] != null && record[key] != undefined) {
                //@ts-ignore
                formData[key] = record[key]
            }
        }
        // Object.assign(formData, rest)
        // 确保弹窗组件也更新了数据
        nextTick(() => {
            popupRef.value?.setFormData(formData)
        })
    }

}

const handleSubmit = async () => {
    try {
        mode.value === 'add' ? await addDepartment(formData) : await editDepartment(formData)
        popupRef.value?.close()
        popupRef.value?.closeLoading()
        emits('success')
    } catch (error) {
        popupRef.value?.closeLoading()
    }
}

const handleCancel = () => {
    popupRef.value?.close()
}

defineExpose({
    open,
    setFormData
})

</script>
